package cn.afactory.tygz.ui.base.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangyouguo356 on 2015/2/10.
 */
public abstract class BaseListAdapter<T, VH extends BaseListAdapter.ViewHolder> extends BaseAdapter {
    protected List<T> mDataList = new ArrayList<T>();
    protected Context mContext;
    protected LayoutInflater mLayoutInflater;

    public BaseListAdapter(Context ctx) {
        this(ctx, null);
    }

    public BaseListAdapter(Context ctx, List<T> listData) {
        mContext = ctx;
        mLayoutInflater = LayoutInflater.from(mContext);
        if (listData != null) {
            this.mDataList = listData;
        }
    }

    @Override
    public int getCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    @Override
    public T getItem(int position) {
        return mDataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        VH vh = null;
        if (convertView == null) {
            convertView = newView(position, mLayoutInflater, parent);
            vh = onViewHolderCreate(position, convertView);
            convertView.setTag(vh);
        } else {
            vh = (VH) convertView.getTag();
        }

        onBindViewHolder(position, getItem(position), vh);
        return convertView;
    }

    public void addDataAll(List<T> listData) {
        addDataAll(listData, true);
    }

    public void addDataAll(List<T> listData, boolean clear) {
        if (clear) {
            mDataList.clear();
        }
        mDataList.addAll(listData);
        notifyDataSetChanged();
    }

    public void addData(T t) {
        mDataList.add(t);
        notifyDataSetChanged();
    }

    public void cleanAll() {
        mDataList.clear();
    }

    public abstract View newView(int position, LayoutInflater inflater, ViewGroup parent);

    public abstract VH onViewHolderCreate(int position, View view);

    public abstract void onBindViewHolder(int position, T itemData, VH vh);

    public static abstract class ViewHolder {
        View rootView;

        public ViewHolder() {
        }

        public ViewHolder(View view) {
            rootView = view;
        }
    }
}
